import { createAlova } from 'alova'
import VueHook from 'alova/vue'
import GlobalFetch from 'alova/GlobalFetch'
import { createServerTokenAuthentication } from '@alova/scene-vue'
import qs from 'qs'
import {
  handleBusinessError,
  handleResponseError,
  handleServiceResult,
} from './handle'
import {
  DEFAULT_ALOVA_OPTIONS,
  DEFAULT_BACKEND_OPTIONS,
} from './config'
import { local } from '@/utils'
import { router } from '@/router'
import { useRouteStore } from '@/store/route'
import { useTabStore } from '@/store/tab'
// 是否显示重新登录
export const isRelogin = { show: false };
const { onAuthRequired } = createServerTokenAuthentication({
  // 添加token到请求头
  assignToken: (method) => {
    method.config.headers.Authorization = `Bearer ${local.get('token')}`
    method.config.headers.token = `${local.get('token')}`
  },
})

// docs path of alova.js https://alova.js.org/
export function createAlovaInstance(
  alovaConfig: Service.AlovaConfig,
  backendConfig?: Service.BackendConfig,
) {
  const _backendConfig = { ...DEFAULT_BACKEND_OPTIONS, ...backendConfig }
  const _alovaConfig = { ...DEFAULT_ALOVA_OPTIONS, ...alovaConfig }

  return createAlova({
    statesHook: VueHook,
    requestAdapter: GlobalFetch(),
    localCache: null,
    baseURL: _alovaConfig.baseURL,
    timeout: _alovaConfig.timeout,

    beforeRequest: onAuthRequired((method) => {
      if (method.meta?.isFormPost) {
        method.config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
        method.data = qs.stringify(method.data)
      }
      alovaConfig.beforeRequest?.(method)
    }),
    responded: {
      // 请求成功的拦截器
      onSuccess: async (response, method) => {
        const { status } = response

        if (status === 200) {
          // 返回blob数据
          if (method.meta?.isBlob)
            return response.blob()

          // 返回json数据
          const apiData = await response.json()

          // 请求成功
          if (apiData[_backendConfig.codeKey] === _backendConfig.successCode)
            return handleServiceResult(apiData)
          // 身份验证过期
          if (apiData[_backendConfig.codeKey] === 401) {
            if (!isRelogin.show) {
              isRelogin.show = true;
              window.$dialog.warning({
                title: `提醒`,
                content: `登录状态已过期，您可以继续留在该页面，或者重新登录`,
                positiveText: "重新登录",
                negativeText: "取消",
                onPositiveClick: () => {
                  isRelogin.show = false;
                  // 清除缓存
                  local.remove('token')
                  local.remove('userInfo')
                  // 清空路由、菜单等数据
                  const routeStore = useRouteStore()
                  routeStore.resetRouteStore()
                  // 清空标签栏数据
                  const tabStore = useTabStore()
                  tabStore.clearAllTabs()
                  const route = unref(router.currentRoute)
                  // 重定向到登录页
                  if (route.meta.requiresAuth) {
                    router.push({
                      name: 'login',
                      query: {
                        redirect: route.fullPath,
                      },
                    })
                  }
                },
                onNegativeClick: () => {
                  isRelogin.show = false;
                },
              });
            }
          }
          // "123"
          // 业务请求失败
          const errorResult = handleBusinessError(apiData, _backendConfig)
          return handleServiceResult(errorResult, false)
        }
        // 接口请求失败
        const errorResult = handleResponseError(response)
        return handleServiceResult(errorResult, false)
      },
      onError: (error, method) => {
        const tip = `[${method.type}] - [${method.url}] - ${error.message}`
        window.$message?.warning(tip)
      },

      onComplete: async (_method) => {
        // 处理请求完成逻辑
      },
    },
  })
}
